package com.aaa.ssm.controller;

import com.aaa.ssm.entity.StudentQuery;
import com.aaa.ssm.entity.StudentVO;
import com.aaa.ssm.service.StudentService;
import com.aaa.ssm.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author AUSU
 * @version 1.0
 * 创建时间：2025/3/22 15:47
 */
@RestController
@RequestMapping("stu")
public class StudentController {

    private static final String STORE_DIR = "F:/ziliao/AAA/img/";
    private static final String BASE_URL = "http://127.0.0.1:8080/ssm/";
    @Autowired
    private StudentService studentService;

    @PostMapping("query")
    public AjaxResult queryStudent (StudentQuery query){

        return studentService.queryStudent(query);
    }

    @DeleteMapping("delete/{id}")
    public AjaxResult deleteStudent (@PathVariable("id") Integer id){

        return studentService.deleteStudent(id);
    }

    @PostMapping("add")
    public AjaxResult addStudent (StudentVO s){

        return studentService.addStudent(s);
    }

    @GetMapping("get/{id}")
    public AjaxResult getStudentById (@PathVariable("id") Integer id){

        return studentService.getStudentById(id);
    }
    @PutMapping
    public AjaxResult updateStudentById (StudentVO s){

        return studentService.updateStudentById(s);
    }

    @RequestMapping("upload")
    public AjaxResult upload (MultipartFile file){

        if (file.isEmpty()){
            return AjaxResult.error("上传文件为空");
        }

        try{
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String randomFileName = UUID.randomUUID().toString() + fileExtension;
            String filePath = STORE_DIR + randomFileName;
            File dest = new File(filePath);
            if (!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs();
            }
            FileCopyUtils.copy(file.getInputStream(),new java.io.FileOutputStream(dest));
            String accessUrl = BASE_URL + randomFileName;
            return AjaxResult.success(accessUrl);
        }catch (IOException e){
            e.printStackTrace();
            return AjaxResult.error("文件上传失败");
        }
    }
}
